package com.kuang.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @program: juc
 * @description: CompletableFuture串行执行
 * @author: 陈恩涛
 * @create: 2021-03-24 15:46
 **/
public class Main {
    public static void main(String[] args) throws Exception {
        // 两个CompletableFuture执行异步查询:
        CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> {
            return queryCode("张三", "https://www.baidu.com");
        });

        CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> {
            return queryCode("李四", "https://www.kuangstudy.com");
        });

        // 用anyOf合并为一个新的CompletableFuture:
        CompletableFuture<Object> cf3 = CompletableFuture.anyOf(cf1, cf2);

        // 两个CompletableFuture执行异步查询:
        CompletableFuture<Double> cf4 = cf3.thenApplyAsync((code) -> {
            return fetchPrice((String) code, "https://www.baidu.com");
        });

        CompletableFuture<Double> cf5 = cf3.thenApplyAsync((code) -> {
            return fetchPrice((String) code, "https://www.kuangstudy.com");
        });

        // 用anyOf合并为一个新的CompletableFuture:

        CompletableFuture<Object> cf6 = CompletableFuture.anyOf(cf4, cf5);

        // 最终结果:
        cf6.thenAccept((price) ->{
            System.out.println("price: " +price);
        });

        // 主线程不要立刻结束，否则CompletableFuture默认使用的线程池会立刻关闭:
        TimeUnit.SECONDS.sleep(5);
    }

    static String queryCode(String name, String url) {
        System.out.println("query code from " + url + "...");
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
        }
        return "601857";
    }

    static Double fetchPrice(String code, String url) {
        System.out.println("query price from " + url + "...");
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
        }
        return 5 + Math.random() * 20;
    }
}

